package com.example.myapplication.room.manager;

import android.content.Context;
import android.os.AsyncTask;
import com.example.myapplication.room.dao.StudentDao;
import com.example.myapplication.room.database.StudentDatabase;
import com.example.myapplication.room.entity.Student;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sjh
 * @Description
 * @create 2022/3/16 10:40
 */
public class DBEngine {

    private StudentDao studentDao;

    public DBEngine(Context context) {
        StudentDatabase instance = StudentDatabase.getInstance(context);
        studentDao = instance.getStudentDao();
    }

    //dao 增删改查

    //selectAll查询
    public List<Student> selectAllStudents() {
        try {
            return new SelectAllAsyncTask(studentDao).execute().get();
        } catch (Exception e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    //insert插入
    public void insertStudents(Student... students) {
        new InsertAsyncTask(studentDao).execute(students);
    }

    //异步线程
    static class SelectAllAsyncTask extends AsyncTask<Void, Void, List<Student>> {

        private StudentDao dao;

        public SelectAllAsyncTask(StudentDao studentDao) {
            dao = studentDao;
        }

        @Override
        protected List<Student> doInBackground(Void... voids) {
            return dao.getAllStudent();
        }
    }

    static class InsertAsyncTask extends AsyncTask<Student, Void, Void> {

        private StudentDao dao;

        public InsertAsyncTask(StudentDao studentDao) {
            dao = studentDao;
        }

        @Override
        protected Void doInBackground(Student... students) {
            dao.insertStudents(students);
            return null;
        }
    }

}
